package com.wsjc.manager.service.rpc.data.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.wsjc.common.core.constants.CommonConst;
import com.wsjc.common.core.dao.db.TableRoute;
import com.wsjc.common.core.page.PageBean;
import com.wsjc.common.core.page.PageParam;
import com.wsjc.common.solr.SolrClientUtils;
import com.wsjc.manager.dao.sterilization.WjSterilizationDao;
import com.wsjc.manager.entity.WjSterilization;
import com.wsjc.manager.entity.vo.PcSterilizationVo;
import com.wsjc.manager.service.rpc.data.WjCollectionDataService;

@Service("wjCollectionDataService")
public class WjCollectionDataServiceImpl implements WjCollectionDataService{
	
	private Logger logger = LoggerFactory.getLogger(WjCollectionDataServiceImpl.class);

	@Autowired
	private SolrClientUtils solrClientUtils ;
	
	@Autowired
	private WjSterilizationDao wjSterilizationDaoImpl ;
	
	
	
	
	@Override
	public PageBean search(Map<String, Object> params, int page, int rows, String dataType) throws Exception {
		
		//返回值对象
		PageBean pageBean = new PageBean();
		
		//创建查询对象
		SolrQuery query = new SolrQuery();
		
		//设置查询条件
		setSolrQuery(query, params);
		
		//设置分页
		query.setStart((page - 1) * rows);
		query.setRows(rows);
		//设置默认搜素域
		query.set("df", "data_keywords");
		//设置高亮显示
//		query.setHighlight(true);
//		query.addHighlightField("item_title");
//		query.setHighlightSimplePre("<em style=\"color:green\">");
//		query.setHighlightSimplePost("</em>");
		//执行查询
		QueryResponse queryResponse = solrClientUtils.queryCase(query); 
		
		// 输出查询结果集
		SolrDocumentList solrDocumentList = queryResponse.getResults();
		
		//取高亮显示
//		Map<String, Map<String, List< String>>> highlighting = queryResponse.getHighlighting();
		
		//取查询结果总数量
		pageBean.setTotalCount(solrDocumentList.getNumFound());
		
		switch (dataType) {
		
			case "00S":
				//检测数据基类
				List<PcSterilizationVo> dataList = new ArrayList<PcSterilizationVo>();
				dataList = getSterilizationData(queryResponse) ;
//				dataList = getData(solrDocumentList, highlighting) ;
				pageBean.setRecordList(dataList);
				break;
			case "02":
				
				break;
	
			default:
				break;
		}
	 
		//计算查询结果总页数
		long totalCount = queryResponse.getResults().getNumFound();
		long pageCount = totalCount / rows;
		if (totalCount % rows > 0) {
			pageCount++;
		}
		pageBean.setTotalPage(pageCount);
		pageBean.setCurrentPage(page);
		
		return pageBean;
		
	}

	/**
	 * 设置solr 搜索条件
	 * @param query
	 * @param params
	 */
	private void setSolrQuery(SolrQuery query, Map<String, Object> params) {
		
		
		String queryWhere = null ;
		/** 时间段 **/
		if(null != params.get(CommonConst.SEARCH_DATA_CONDITION_START_TIME) && null != params.get(CommonConst.SEARCH_DATA_CONDITION_END_TIME)){
			// 50 <= price <= 200
//			query.setQuery("price:[50 TO 200]");
			queryWhere = "detectionTime:[" + params.get(CommonConst.SEARCH_DATA_CONDITION_START_TIME) +" TO " + params.get(CommonConst.SEARCH_DATA_CONDITION_END_TIME) +"]" ;
//			query.setQuery("detectionTime:[" + params.get(CommonConst.SEARCH_DATA_CONDITION_START_TIME) +" TO " + params.get(CommonConst.SEARCH_DATA_CONDITION_END_TIME) +"]");
		}
		/** 医院类别 **/
		if(null != params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_TYPE)){
			// OR 或者
//			query.setQuery("name:apple OR manu:apache");
			if(null != queryWhere){
				queryWhere = queryWhere + " AND " + "hospitalType:" + params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_TYPE) ;
			}else{
				queryWhere = "hospitalType:" + params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_TYPE) ;
			}
//			query.setQuery("hospitalType:" + params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_TYPE));
		}
		/** 医院名称 **/
		if(null != params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_NAME)){
			// 查询name包含solr apple
//			query.setQuery("name:solr,apple");
			if(null != queryWhere){
				queryWhere = queryWhere + " AND " + "hospitalName:" + params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_NAME)+"*" ;
			}else{
				queryWhere = "hospitalName:" + params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_NAME) +"*" ;
			}
//			query.setQuery("hospitalName:" + params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_NAME));
		}
		/** 医院id **/
		if(null != params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_ID)){
			// 查询name包含solr apple
//			query.setQuery("name:solr,apple");
			if(null != queryWhere){
				queryWhere = queryWhere + " AND " + "id:" + params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_ID) ;
			}else{
				queryWhere = "id:" + params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_NAME) ;
			}
//			query.setQuery("hospitalName:" + params.get(CommonConst.SEARCH_DATA_CONDITION_HOSPITAL_NAME));
		}
		/** 检测结果 **/
		if(null != params.get(CommonConst.SEARCH_DATA_CONDITION_DETECTIONRESULT)){
			if(null != queryWhere){
				queryWhere = queryWhere + " AND " + "detectionResult:" + params.get(CommonConst.SEARCH_DATA_CONDITION_DETECTIONRESULT) ;
			}else{
				queryWhere = "detectionResult:" + params.get(CommonConst.SEARCH_DATA_CONDITION_DETECTIONRESULT) ;
			}
//			query.setQuery("detectionResult:" + params.get(CommonConst.SEARCH_DATA_CONDITION_DETECTIONRESULT));
		}
		
		/** 区域 **/
		if(null != params.get(CommonConst.SEARCH_DATA_CONDITION_SCOPE)){
			
			/** 获取区域级别 **/
			String level = obtainScopeLevel(params.get(CommonConst.SEARCH_DATA_CONDITION_SCOPE).toString()) ;
			String where = "";
			switch (level){
			
				case CommonConst.SCOPE_LEVEL_COUNTRY:
					logger.info("DATA-COLLECTION|WjCollectionDataServiceImpl-setSolrQuery()|搜索全国不做参数处理:" + params.toString());
					break;
				case CommonConst.SCOPE_LEVEL_PROVINCE:
					String pScope = params.get(CommonConst.SEARCH_DATA_CONDITION_SCOPE).toString() ;
					pScope = pScope.substring(0, 2) ;
					where = "areaId:" + pScope +"*";
//					query.setQuery("scope:" + pScope );
					break;
				case CommonConst.SCOPE_LEVEL_CITY:
					String cScope = params.get(CommonConst.SEARCH_DATA_CONDITION_SCOPE).toString() ;
					cScope = cScope.substring(0, 4) ;
					where = "areaId:" + cScope +"*";
//					query.setQuery("scope:" + cScope);
					
					break;
				case CommonConst.SCOPE_LEVEL_AREA:
					String aScope = params.get(CommonConst.SEARCH_DATA_CONDITION_SCOPE).toString() ;
					where = "areaId:" + aScope;
//					query.setQuery("scope:" + aScope);
					break;
				default:
					logger.info("DATA-COLLECTION|WjCollectionDataServiceImpl-setSolrQuery()|参数错误:" + params.toString());
					break;
			}
			
			if(null != queryWhere){
				queryWhere = queryWhere + " AND " + where;
			}else{
				queryWhere =  where;
			}
		}
		
		logger.info("DATA-COLLECTION|WjCollectionDataServiceImpl-setSolrQuery()|where:" + queryWhere);
		query.setQuery(queryWhere);
		// 用版本号/或者时间戳--控制时间倒叙
		query.setSort("detectionTimestamp", ORDER.desc);//排序：名称倒序 
	}

	/**
	 * 获得区域级别
	 * @param string
	 */
	public String obtainScopeLevel(String scope) {
		
		String level = scope.substring(0, 2);
		if(level.equals("00")){
			return CommonConst.SCOPE_LEVEL_COUNTRY;
		}
		level = scope.substring(2, 6);
		if(level.equals("0000")){
			return CommonConst.SCOPE_LEVEL_PROVINCE;
		}
		level = scope.substring(4, 6);
		if(level.equals("00")){
			return CommonConst.SCOPE_LEVEL_CITY;
		}
		return CommonConst.SCOPE_LEVEL_AREA;
		
	}

	/**
	 * 逐条获取并设置高亮
	 * @param solrDocumentList
	 * @param highlighting
	 * @return
	 */
	private List<PcSterilizationVo> getData(SolrDocumentList solrDocumentList, Map<String, Map<String, List<String>>> highlighting) {
		
		List<PcSterilizationVo> pcSterilizationVos = Lists.newArrayList() ;
		//取商品列表
		for (SolrDocument solrDocument : solrDocumentList) {
			//创建一商品对象
			PcSterilizationVo sterilizationVo = new PcSterilizationVo();
			
			/*item.setId((String) solrDocument.get("id"));
			//取高亮显示的结果
			List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
			String title = "";
			if (list != null && list.size()>0) {
				title = list.get(0);
			} else {
				title = (String) solrDocument.get("item_title");
			}
			item.setTitle(title);
			item.setImage((String) solrDocument.get("item_image"));
			item.setPrice((long) solrDocument.get("item_price"));
			item.setSell_point((String) solrDocument.get("item_sell_point"));
			item.setCategory_name((String) solrDocument.get("item_category_name"));*/
			
			//灭菌效果数据列表
			pcSterilizationVos.add(sterilizationVo);
			
		}
		return null;
	}
	
	
	/**
	 * 获取灭菌效果数据
	 * @param solrDocumentList
	 * @param highlighting
	 * @return
	 */
	private List<PcSterilizationVo> getSterilizationData(QueryResponse queryResponse) {
		List<PcSterilizationVo> sterilizations = queryResponse.getBeans(PcSterilizationVo.class);
		return sterilizations;
	}

	@Override
	public PageBean<WjSterilization> listDataPage(PageParam pageParam, Map<String, Object> paramMap, String scope,String dataType) {

		switch (dataType) {
			case "00S":
				// 检测数据基类
				PageBean<WjSterilization> pageBean = listSterilizationDataPage(pageParam, paramMap, scope);
				// dataList = getData(solrDocumentList, highlighting) ;
				return pageBean;
			case "02":
	
				break;
	
			default:
				break;
			}

		return null ;
	}
	
	/**
	 * 获取灭菌数据
	 * @param pageParam
	 * @param paramMap
	 * @param scope
	 * @return
	 */
	public PageBean<WjSterilization> listSterilizationDataPage(PageParam pageParam, Map<String, Object> paramMap, String scope) {
		
		paramMap.put("tableName", CommonConst.WJ_STERILIZATION) ;
		TableRoute.setTableName(paramMap, scope);

		// scope 区级 要作为sql 条件
		String level = this.obtainScopeLevel(scope);
		if(level.equals(CommonConst.SCOPE_LEVEL_AREA)){
			paramMap.put("areaId", scope);
		}
		PageBean<WjSterilization> pageBean = wjSterilizationDaoImpl.listPage(pageParam, paramMap);
		
		return pageBean;
	}

	
	
	
	
	
	public static void main(String[] args) {
		System.out.println(System.currentTimeMillis());
	}
	
	
	
	
	

}
